import React, { useState, useEffect, useCallback } from "react";
import { Table, Button, message, Pagination, Input, Checkbox } from "antd";
import { IApplySchool } from "@/interface/student";
import { debounce } from "lodash";
import api from "@/fetch";

import "./index.less";

const checks = [
  {
    openStatus: "-1",
    name: "所有",
  },
  {
    openStatus: "0",
    name: "申请中",
  },
  {
    openStatus: "1",
    name: "已开通",
  },
  {
    openStatus: "2",
    name: "已拒绝",
  },
  {
    openStatus: "3",
    name: "下架",
  },
];

const ManageSchool: React.FC = () => {
  const [data, setData] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState<{
    schoolName: string;
    openStatus: string;
  }>({
    schoolName: "",
    openStatus: "-1",
  });

  const fetchData = useCallback(
    debounce(async (currentPage, pageSize, searchParams) => {
      setLoading(true);

      const search: Partial<{ schoolName: string; openStatus: string }> = {};

      if (searchParams.schoolName !== "") {
        search["schoolName"] = searchParams.schoolName;
      }

      if (searchParams.openStatus !== "") {
        search["openStatus"] = searchParams.openStatus;
      }

      const params = {
        ...search,
        page: currentPage - 1,
        pageSize,
      };

      try {
        const res = await api.get("/api/v1/admin/school/page", params);
        setData(res.data.result);
        setTotal(res.data.total);
      } catch (error) {
        message.error(error?.message || "获取审核学校列表失败");
      } finally {
        setLoading(false);
      }
    }, 300),
    [],
  );

  useEffect(() => {
    fetchData(currentPage, pageSize, searchParams);
  }, [currentPage, pageSize, searchParams]);

  const handlePageChange = (newPage: number, newPageSize: number) => {
    currentPage !== newPage && setCurrentPage(newPage);
    pageSize !== newPageSize && setPageSize(newPageSize);
  };

  const handleSearchChange = (field: string, value: string) => {
    if (field === "openStatus" && searchParams.openStatus === value) {
      return;
    }

    setSearchParams({
      ...searchParams,
      [field]: value,
    });
  };

  const handleResult = async (school: IApplySchool, result: 1 | 2) => {
    // 处理通过逻辑...
    setLoading(true);
    try {
      await api.post("/api/v1/admin/school/review", {
        schoolId: school.schoolId,
        reviewResult: result,
      });
      message.success(result === 1 ? "已通过" : "已拒绝");
      fetchData(currentPage, pageSize, searchParams);
    } catch (error) {
      message.error(
        error?.message || result === 1
          ? "通过失败，请稍后再试"
          : "拒绝失败，请稍后再试",
      );
    } finally {
      setLoading(false);
    }
  };

  const columns = [
    { title: "学校名", dataIndex: "schoolName", key: "schoolName" },
    { title: "审核状态", dataIndex: "openStatus", key: "openStatus" },
    {
      title: "操作",
      dataIndex: "actions",
      key: "actions",
      render: (_: string, school: IApplySchool) => {
        return school.openStatus === 0 ? (
          <span>
            <Button type="primary" onClick={() => handleResult(school, 1)}>
              通过
            </Button>
            <Button
              danger
              onClick={() => handleResult(school, 2)}
              style={{ marginLeft: "8px" }}
            >
              不通过
            </Button>
          </span>
        ) : null;
      },
    },
  ];

  return (
    <div className="manage-school-container">
      {!window.useData.getState().userInfo?.token && (
        <h1>没有登录，发送请求都是失败的噢</h1>
      )}
      <div className="manage-school-header">
        <Input
          allowClear
          className="custom-input"
          placeholder="搜索学校名"
          value={searchParams.schoolName}
          onChange={(e) => handleSearchChange("schoolName", e.target.value)}
        />
        <div style={{ marginLeft: "16px" }}>
          审核状态：
          {checks.map((check) => (
            <Checkbox
              key={check.openStatus}
              checked={check.openStatus === searchParams.openStatus}
              onChange={() =>
                handleSearchChange("openStatus", check.openStatus)
              }
            >
              {check.name}
            </Checkbox>
          ))}
        </div>
      </div>

      <Table
        dataSource={data}
        columns={columns}
        rowKey="schoolId"
        pagination={false}
        loading={loading}
      />
      <Pagination
        current={currentPage}
        pageSize={pageSize}
        total={total}
        onChange={handlePageChange}
        showSizeChanger
        pageSizeOptions={["10", "20", "50", "100"]}
        style={{ marginTop: "16px", textAlign: "right" }}
      />
    </div>
  );
};

export default ManageSchool;
